package org.skydiveapp;

import org.skydiveapplibrary.ui.DrawingView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class LogEntryDiagramActivity extends Activity
{
	// menus
	private MenuItem saveMenu;
	private MenuItem clearMenu;
	
	@Override 
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    	
    	setContentView(R.layout.log_entry_diagram_view);
    	
    	// init header
    	TextView headerText = (TextView)findViewById(R.id.FormHeaderTextView);
    	headerText.setText(R.string.log_entry_diagram_header);
    	
    	// get drawingview 
    	DrawingView drawingView = (DrawingView)findViewById(R.id.LogEntryDiagramDrawingView);
    	// load data
    	byte[] data = getIntent().getByteArrayExtra(Constants.EXTRA_DIAGRAM);
    	if (data != null)
    	{
    		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    		drawingView.drawBitmap(bitmap);
    	}
    }
	
	private void clear()
	{
		DrawingView drawingView = (DrawingView)findViewById(R.id.LogEntryDiagramDrawingView);
		drawingView.clear();
	}
	
	private void save()
	{
		DrawingView drawingView = (DrawingView)findViewById(R.id.LogEntryDiagramDrawingView);
		
		if (!drawingView.isBitmapChanged())
		{
			// cancelled if not modified
			setResult(RESULT_CANCELED);
		}
		else
		{
			// get image data
			byte[] data = drawingView.getImageData();
			// set result intent
			Intent intent = new Intent();
			intent.putExtra(Constants.EXTRA_DIAGRAM, data);
			setResult(RESULT_OK, intent);
		}

		// finish
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		clearMenu = menu.add(R.string.log_entry_diagram_clear);
		clearMenu.setIcon(R.drawable.ic_menu_clear);
		
		saveMenu = menu.add(R.string.done_button);
		saveMenu.setIcon(R.drawable.ic_menu_save);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item == saveMenu)
		{
			save();
        	return true;
		}
		else if (item == clearMenu)
		{
			clear();
        	return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onBackPressed()
	{
		save();
		super.onBackPressed();
	}
}
